﻿/**
 * Header should be here
 *
 * @author Yuriy Shapovalov
 */

/// <reference path="~/Scripts/lib/knockout-2.2.0.js" />

define('timer',
    ['ko', 'time-range'],
    function (ko, timerange) {
        /// ctor
        var Timer = function (activityId) {
            var self = this;
            self.range = ko.observable(new TimeRange(activityId));
            self.interval = ko.observable();
            self.status = ko.observable(false);
            self.hours = ko.observable();
            self.minutes = ko.observable();
            self.seconds = ko.observable();
            self.time = ko.observable();
        };
        
        Timer.prototype = function () {
            var tick = function (callback) {
                range.end = new Date();
                secondsDiff = (range.end.valueOf() - range.start.valueOf());
                var tmp = new Date(secondsDiff);
                hours = tmp.getUTCHours();
                minutes = tmp.getUTCMinutes();
                seconds = tmp.getUTCSeconds();

                time(hours + ":" + normalizeTime(minutes) + ":" + normalizeTime(seconds));
                // invokeCallback(result);
            },

            normalizeTime = function (time) {
                return (time < 10) ? (time = '0' + time) : time;
            },

            start = function () {
                status = true;
                range.start = new Date();
                // TODO: Update model in localstorage, send data to server
                interval = setInterval(tick, 500);
            },

            stop = function () {
                window.clearInterval(interval);
                status = false;
                range.locked = true;
                // TODO: Add new recored to log, localstorage and send to server
                return range;
            };

            return {
                range: self.range,
                status: self.status,
                start: self.start,
                stop: self.stop,
                time: self.time
            }
        }();

        return Timer;

       
    });